package com.didd.core.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.didd.core.common.base.RpcResponse;
import com.didd.core.security.LoginResultCode;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @author diddd
 * @date 2021/11/11 4:07 下午
 */
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        RpcResponse<Void> resp;

        if (authException instanceof BadCredentialsException) {
            resp = RpcResponse.fail(LoginResultCode.LOGIN_NAME_PASSWORD_ERROR);
        } else if (authException instanceof DisabledException) {
            resp = RpcResponse.fail(LoginResultCode.ACCOUNT_IS_DISABLE);
        } else if (authException instanceof SessionAuthenticationException) {
            resp = RpcResponse.fail(LoginResultCode.TOKEN_IS_ERROR);
        } else if (authException instanceof InsufficientAuthenticationException) {
            resp = RpcResponse.fail(LoginResultCode.TOKEN_IS_ERROR);
        } else {
            resp = RpcResponse.fail(authException.getMessage());
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        ObjectMapper objectMapper = new ObjectMapper();
        String resBody = objectMapper.writeValueAsString(resp);
        PrintWriter printWriter = response.getWriter();
        printWriter.print(resBody);
        printWriter.flush();
        printWriter.close();
    }

}
